<template>
  <div class="historical-record">
    <div class="historical-record-title" ref="scrollContainer">
      <van-loading v-if="isLoading" />
      <span v-if="flagType==''">
      {{ flag ? "加载完成" : "" }}

      </span>
      {{flagType}}
    </div>
    <!-- <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh"
      :disabled="isDisabled"
      @scroll="handleScroll"
    >
      <div class="historical-record-title" ref="scrollContainer">
        {{ flag ? "加载完成" : "" }}
        <slot></slot>
      </div>
    </van-pull-refresh>-->
  </div>
</template>

<script>
import { detectDeviceType, _getRandomUserId, _getSessionCode, getUrlParams, getReqid, getRandomStr } from "@/utils/common";
// import { version } from "vue/types/umd";
export default {
  name: "historicalRecord",
  props: {
    session: Object,
  },
  data() {
    return {
      isLoading: false,
      pageNo: 0,
      answer: [],
      flag: false,
      isDisabled: false,
      scrollPosition: 0,
      flagType:''
    };
  },
  // watch: {
  //   flag: {
  //     immediate: true,
  //     handler(newVal) {
  //       if(newVal){
  //         this.$emit("flagType", newVal);

  //       }
  //     },
  //   },
  // },
  created() {},
  // mounted() {
  //   this.$refs.scrollContainer.addEventListener("scroll", this.handleScroll);
  // },
  // beforeDestroy() {
  //   this.$refs.scrollContainer.removeEventListener("scroll", this.handleScroll);
  // },
  methods: {
    // handleScroll() {
    //   const container = this.$refs.scrollContainer;
    //   this.scrollPosition = container.scrollTop;
    //   this.isDisabled = this.scrollPosition > 0;
    // },
    // onRefresh() {
    //   if (this.scrollPosition === 0) {
    //     this.loadHistory();
    //   } else {
    //     this.isLoading = false;
    //   }
    // },
    parseBlmsession(session, answer) {
      answer.isBlm ? (session.isBlm = answer.isBlm) : (session.isBlm = 0);
      if (session.isBlm == 1) {
        let joji = answer.txt[0].content;
        if (typeof answer.txt[0].content === "string") {
          joji = JSON.parse(answer.txt[0].content);
        }
        let blmData = [];
        session.RobotStreamAnswerParserV3Instance = window.chatSseSdk.createAnswerParse();
        joji.forEach((item) => {
          if (item.is_last) {
            session.blmParseData = blmData;
            return true;
          }
          const parseData = window.chatSseSdk.handleSseData(item, session, true);
          if (!(!parseData || parseData === undefined)) {
            blmData = parseData;
          }
        });
        return blmData;
      } else {
        console.log(1111, this, answer);
        this.$parent.renderNormalData({ answer: [answer] }, session);
      }
    },
    loadHistory() {
      if(this.flagType!=''){
return
      }
      this.isLoading = true;
      

      this.$emit("isloadHistory", true);
      if (this.pageNo >= 0 && !this.flag) {

        this.pageNo++;
      }
      let channel = "other";
      let source = "b_customer_trail_04";
      const urls = getUrlParams();
      let userId = _getRandomUserId();
      const obj = {
        direct_mode: `["hisData"]`,
        question: "",
        add_info: JSON.stringify({
          hisData: {
            pageNo: this.pageNo,
            messagelype: ["robot ", "hcs"],
            entranceld: urls.entranceId,
            stockName: "同花顺",
          },
        }),
        source: source,
        user_name: getRandomStr(10),
        version: "2.0",
        answerChannel: `${detectDeviceType()}_${channel}`,
        user_id: userId,
        secondary_intent: "",
        sdk_version: "",
        mode: "preLocal",
        logid: `${userId}${new Date().getTime()}`,
        reqid: getReqid(),
      };
      const formParams = new URLSearchParams();
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          formParams.append(key, obj[key]);
        }
      }
      let url = "/saas/robot/center/";
      // 拼接参数到URL
      url += "?" + formParams.toString();
      fetch(url, {
        method: "GET",
        params: formParams,
      })
        .then((response) => response.json())
        .then((res) => {
          res.answer.forEach((item) => {
            let session = {
              sessionId: "123",
              isBlm: -1,
              isSignal: 0,
              blmParseData: [],
              blmOpts: {
                showStep: false,
                answerSatge: window.chatSseSdk.ANSWER_STAGE.UNKNOW,
              },
              answers: {}, // 推荐问句数据格式
              response: {},
            };

            const data = this.parseBlmsession(session, item);
            item.session = {
              ...session,
              blmParseData: data,
              isBlm: session.isBlm || 0,
            };
          });

            
          if (res.answer.length === 0) {
            this.flag = true;
            this.flagType='已加载全部历史数据'
            this.pageNo = 1; // 重置页码

          } else {
            this.flag = false;
            this.$emit("flagType", true);
            this.$emit("loadHistory", res.answer, this.pageNo);
          }
          setTimeout(() => {
            this.isLoading = false;
            this.$emit("isloadHistory", false);
          }, 1500);
        });
    },
  },
};
</script>

<style lang="less" scoped>
.historical-record {
  padding-top: 30px;
}
</style>
